import axios from 'axios';
import { ElMessage } from 'element-plus';

export const baseURL = 'http://localhost:8888';
// export const baseURL = 'http://ycy.free.svipss.top';  //线上地址

const service = axios.create({
  baseURL: baseURL,
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

//请求拦截
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');

    if (!config.headers) config.headers = {};

    if (token) config.headers.token = token;
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

//响应拦截
service.interceptors.response.use(
  res => {
    const code = res.status;
    if (code === 200) {
      return Promise.resolve(res.data);
    } else {
      ElMessage.error(res.data.message);
      return Promise.reject(res);
    }
  },
  err => {
    ElMessage.error('服务器错误');
    return Promise.reject(err);
  }
);

export default service;
